package com.example.money.test;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextInputActivity extends AppCompatActivity implements View.OnClickListener {

    private TextInputLayout mUserlayout;
    private TextInputLayout mPasslayout;
    private EditText edtUser;
    private EditText edtPass;
    private Button btn_login;

    private static String EMAIL_PATTERN = "^[a-zA-Z0-9#_~!$&'()*+,;=:.\"(),:;<>@\\[\\]\\\\]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*$";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_input_layout);

        init();
    }

    private void init() {
        mUserlayout = findViewById(R.id.id_input_user);
        mPasslayout = findViewById(R.id.id_input_pass);
        edtUser = findViewById(R.id.id_user_edit);
        edtPass = findViewById(R.id.id_pass_edit);
        btn_login = findViewById(R.id.login);

        btn_login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.login){
            if(!checkLength()){
                mPasslayout.setErrorEnabled(true);
                mPasslayout.setError("请输入正确的密码长度");
            }
            if(!checkFormat() ){
                mUserlayout.setErrorEnabled(true);
                mUserlayout.setError("请输入正确的邮箱地址");
            }else{
                mPasslayout.setErrorEnabled(false);
                mUserlayout.setErrorEnabled(false);
                Toast.makeText(this,"login successed",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean checkFormat() {
        //采用邮箱教研正则
        Pattern p = Pattern.compile(EMAIL_PATTERN);
        String username = String.valueOf(edtUser.getText());
        Matcher m = p.matcher(username);
        return m.matches();
    }

    private boolean checkLength() {
        if(edtPass.getText().length() < 6 || edtPass.getText().length() > 16){

            return false;
        }
        return true;
    }
}
